﻿using Agile.Infra.Core.Agile.Extensions;
using Agile.Infra.Pay.WxPay.Models;
using Newtonsoft.Json;
using System.Text;

namespace Agile.Infra.Pay.WxPay
{
    public partial class WxPayService
    {
        public async Task<WxProfitSharingResponse> ProfitSharingAsync(WxProfitSharingRequest request)
        {
            CheckRequestParams(request);
            var requestJson = GetWxProfitSharingRequest(request);
            using (var content = new StringContent(requestJson.ToJsonString(), Encoding.UTF8, "application/json"))
            {
                var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, _wxPayOptions.ServerUrl);
                httpRequestMessage.Content = content;
                var response = await base.HttpRequestAsync(request.TransactionID, httpRequestMessage);

                if (string.IsNullOrWhiteSpace(response))
                {
                    return new WxProfitSharingResponse() { Message = "未返回结果" };
                }
                var result = response.ToJsonObject<WxProfitSharingResponseModel>();

                return new WxProfitSharingResponse
                {
                    Success = true,
                };
            }
        }


        private void CheckRequestParams(WxProfitSharingRequest request)
        {
            if (request.TransactionID.IsNullOrWhiteSpace())
                throw new PayException("微信支付订单不能为空");

            if (request.OutOrderNO.IsNullOrWhiteSpace())
                throw new PayException("商户分账单号不能为空");

            if (request.Receivers == null || request.Receivers.Count == 0)
                throw new PayException("分账接收方不能为空");
        }
        private WxProfitSharingRequestModel GetWxProfitSharingRequest(WxProfitSharingRequest request)
        {
            return new WxProfitSharingRequestModel
            {
                AppID = _wxPayOptions.AppID,
                OutOrderNO = request.OutOrderNO,
                TransactionID = request.TransactionID,
                Receivers = request.Receivers.Select(x => new WxProfitSharingReceiverRequestModel
                {
                    Type = x.Type,
                    Account = x.Account,
                    Name = x.Name,
                    Amount = x.Amount,
                    Description = x.Description
                }).ToList(),
                UnfreezeUnsplit = request.UnfreezeUnsplit
            };
        }

        #region 请求实体
        internal class WxProfitSharingRequestModel
        {
            /// <summary>微信分配的商户appid 示例值：wx8888888888888888</summary>
            [JsonProperty("appid")]
            public string AppID { get; set; }

            /// <summary>微信订单号 示例值：4208450740201411110007820472</summary>
            [JsonProperty("transaction_id")]
            public string TransactionID { get; set; }

            /// <summary>商户分账单号 商户系统内部的分账单号，在商户系统内部唯一，同一分账单号多次请求等同一次。只能是数字、大小写字母_-|*@ </summary>
            [JsonProperty("out_order_no")]
            public string OutOrderNO { get; set; }

            /// <summary>分账接收方列表</summary>
            [JsonProperty("receivers")]
            public List<WxProfitSharingReceiverRequestModel> Receivers { get; set; }

            /// <summary>是否解冻剩余未分资金</summary>
            [JsonProperty("unfreeze_unsplit")]
            public bool UnfreezeUnsplit { get; set; }

        }

        internal class WxProfitSharingReceiverRequestModel
        {
            /// <summary>分账接收方类型  	
            /// 1、MERCHANT_ID：商户号
            /// 2、PERSONAL_OPENID：个人openid（由父商户APPID转换得到）
            /// 示例值：MERCHANT_ID
            /// </summary>
            [JsonProperty("type")]
            public string Type { get; set; }

            /// <summary>分账接收方帐号</summary>
            [JsonProperty("account")]
            public string Account { get; set; }

            /// <summary>分账个人接收方姓名</summary>
            [JsonProperty("name")]
            public string Name { get; set; }

            /// <summary>分账金额，单位为分，只能为整数，不能超过原订单支付金额及最大分账比例金额</summary>
            [JsonProperty("amount")]
            public int Amount { get; set; }

            /// <summary>分账描述</summary>
            [JsonProperty("description")]
            public string Description { get; set; }
        }

        #endregion


        #region 响应实体

        internal class WxProfitSharingResponseModel
        {
            /// <summary>微信订单号 示例值：4208450740201411110007820472</summary>
            [JsonProperty("transaction_id")]
            public string TransactionID { get; set; }

            /// <summary>商户分账单号 商户系统内部的分账单号，在商户系统内部唯一，同一分账单号多次请求等同一次。只能是数字、大小写字母_-|*@ </summary>
            [JsonProperty("out_order_no")]
            public string OutOrderNO { get; set; }

            /// <summary>微信分账单号 </summary>
            [JsonProperty("order_id")]
            public string OrderID { get; set; }

            /// <summary>分账单状态  1、PROCESSING：处理中  2、FINISHED：分账完成 </summary>
            [JsonProperty("state")]
            public string State { get; set; }

            /// <summary>分账接收方列表</summary>
            [JsonProperty("receivers")]
            public List<WxProfitSharingReceiverResponseModel> Receivers { get; set; }
        }

        internal class WxProfitSharingReceiverResponseModel
        {
            /// <summary>分账接收方类型  	
            /// 1、MERCHANT_ID：商户号
            /// 2、PERSONAL_OPENID：个人openid（由父商户APPID转换得到）
            /// 示例值：MERCHANT_ID
            /// </summary>
            [JsonProperty("type")]
            public string Type { get; set; }

            /// <summary>分账接收方帐号</summary>
            [JsonProperty("account")]
            public string Account { get; set; }

            /// <summary>分账金额，单位为分，只能为整数，不能超过原订单支付金额及最大分账比例金额</summary>
            [JsonProperty("amount")]
            public int Amount { get; set; }

            /// <summary>分账描述</summary>
            [JsonProperty("description")]
            public string Description { get; set; }

            /// <summary>分账结果 1、PENDING：待分账 2、SUCCESS：分账成功 3、CLOSED：已关闭</summary>
            [JsonProperty("result")]
            public string Result { get; set; }

            /// <summary>分账失败原因
            /// 分账失败原因。包含以下枚举值：
            /// 1、ACCOUNT_ABNORMAL : 分账接收账户异常
            /// 2、NO_RELATION : 分账关系已解除
            /// 3、RECEIVER_HIGH_RISK : 高风险接收方
            /// 4、RECEIVER_REAL_NAME_NOT_VERIFIED : 接收方未实名
            /// 5、NO_AUTH : 分账权限已解除
            /// 示例值：ACCOUNT_ABNORMAL 
            /// </summary>
            [JsonProperty("fail_reason")]
            public string FailReason { get; set; }

            /// <summary>分账创建时间</summary>
            [JsonProperty("create_time")]
            public string CreateTime { get; set; }

            /// <summary>分账完成时间</summary>
            [JsonProperty("finish_time")]
            public string FinishTime { get; set; }
        }

        #endregion
    }
}
